package com.android.calculator.util;

import java.math.BigDecimal;

public class Arith {
    // 运算精确度
    private static final int DEF_DIV_SCALE = 10;


    /*加法*/
    public static String add(double v1, double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return String.valueOf(b1.add(b2));
    }
    public static String add(String v1, String v2){
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return String.valueOf(b1.add(b2));
    }

    /*减法*/
    public static String sub(String v1, String v2){
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return String.valueOf(b1.subtract(b2));
    }
    public static String sub(double v1, double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return String.valueOf(b1.subtract(b2));
    }

    /*乘法*/
    public static String mul(String v1, String v2){
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return String.valueOf(b1.multiply(b2));
    }
    public static String mul(double v1, double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return String.valueOf(b1.multiply(b2));
    }

    /*除法*/
    public static String div(double v1, double v2){
        return  div(v1, v2, DEF_DIV_SCALE);
    }
    public static String div(String v1, String v2){
        return div(v1, v2, DEF_DIV_SCALE);
    }
    public static String div(double v1, double v2, int scale){
        if(scale < 0){
            throw new IllegalArgumentException("精确度必须是正整数或0");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return String.valueOf(b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP));
    }
    public static String div(String v1, String v2, int scale){
        if(scale < 0){
            throw new IllegalArgumentException("精确度必须是正整数或0");
        }
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        BigDecimal result = null;
        try {
            result = b1.divide(b2);
        }catch (Exception e){
            result = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);
        }
        return String.valueOf(result);
    }
}
